﻿@using SmartCode
@using SmartCode.Db
@model BuildContext
@{
    Layout = "_SqlMapLayout.cshtml";
    var project = Model.Project;
    var dbSource = Model.GetDataSource<DbSource>();
    var buildTask = Model.Build;
    var table = Model.GetCurrentTable();
    var pkCol = table.PKColumn;
    if (pkCol == null)
    {
        throw new SmartCodeException($"{table.Name} can not find PKColumn！");
    }
    var primaryKeyType = pkCol?.LanguageType ?? "int";
    var autoIncrement = table.AutoIncrement;
    var dbPrefix = dbSource.DbProvider.ParameterPrefix;
    var notEqCols = table.Columns.Where(m => m.ConvertedName != m.Name);
    var resultMapName = $"{table.ConvertedName}ResultMap";
    var queryStatementResultMap = table.HasColNameNotEqConvertedName ? $"ResultMap=\"{resultMapName}\"" : "";
}

@section QueryByPage
    {
    <!--获取分页数据-->
    <Statement Id="QueryByPage" @queryStatementResultMap>
        Select TT.* From
        (Select ROW_NUMBER() Over(Order By T.@pkCol.Name Desc) Row_Index,T.* From @table.Name T
        <Include RefId="QueryParams" />) TT
        Where TT.Row_Index Between ((@(dbPrefix)PageIndex-1)*@(dbPrefix)PageSize+1) And (@(dbPrefix)PageIndex*@(dbPrefix)PageSize)
    </Statement>
}
@section GetEntity
    {
    <!--获取表映射实体-->
    <Statement Id="GetEntity" @queryStatementResultMap>
        Select T.* From @table.Name T
        <Where Min="1">
            ROWNUM = 1
        @foreach (var col in table.Columns)
        {
            <IsNotEmpty Prepend="And" Property="@col.ConvertedName">
                T.@col.Name= @($"{dbPrefix}{col.ConvertedName}")
            </IsNotEmpty>
        }
        </Where>
    </Statement>
}

@section Query
    {
    <!--获取数据列-->
    <Statement Id="Query" @queryStatementResultMap>
        select * from (

            SELECT
            T.* From @table.Name T
            <Include RefId="QueryParams"/>
            <Switch Prepend="Order By" Property="OrderBy">
                <Default>
                    T.@pkCol.Name Desc
                </Default>
            </Switch>
        )
        <IsNotEmpty Prepend="where" Property="Taken">
        <![CDATA[
        ROWNUM <= @(dbPrefix)Taken
        ]]>
        </IsNotEmpty>
    </Statement>
}
